import React, { useContext, useEffect, useMemo, useState } from 'react';
import { Button, Tabs } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import { UpdateContrractInfo } from './UpdateContrractInfo';
import { onMouseOutBtn } from '@/utils';
import { UpCircleOutlined, DownCircleOutlined } from '@ant-design/icons';
import { ContractOnlyEditingView } from './ContractOnlyEditingView';
import { UpdateContractBottom } from './UpdateContractBottom';
import { changeNumMoneyToChinese, wordHandChildParam, wordToChildParams, getLoadMapList, getTenantID } from '@/utils';
import { ConractControllerContext, IContractsActionEnum } from '../common';
import { ILoadMapTypeAll } from '@/common';

export const UpdateViewLeft: React.FC = () => {
  /** 获取上下文 */
  const {
    locationID,
    contractDetailInfo,
    curRes,
    pageType,
    contractForm,
    contarctJsonList,
    contractDispatch,
    updteAddOrEdit: { addContractRun, editContractRun, editRecordContractRun, submitRecordContractRun, addAndSubmitContractRun },
  } = useContext(ConractControllerContext);

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}`, //支付方式
    `${getTenantID()}${ILoadMapTypeAll.COMPANY_TAXRATE}`, //税率
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_FIELDTYPE}`, //合同附件类型
    // `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //量化单位
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_TYPE}`, // 合同类型
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}`, // 合同状态
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`,
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`, //供货类别
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //量化单位
    // `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`, //品牌
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_CURRENCYTYPE}`, //币种
  ]);

  /**保存当前选中Tabs 下标 */
  const [tabsInfoPaneInfo, setTabsInfoPaneInfo] = useState<Record<string, any>>({
    tabsPaneKey: '1',
    formObj: {},
  });

  /** 变更记录展开关闭 */
  const [chanageListOpen, setChangeListOpen] = useState<Record<string, any>>({
    allOpenKeys: [],
    openIdKey: [],
  });

  /** 是否统一文本变化 */
  const [isUnifiedText, setIsUnifiedText] = useState<boolean>(false);

  useEffect(() => {
    if (contractDetailInfo?.id) {
      setIsUnifiedText(contractDetailInfo?.templateFlag == 0 ? false : true);
    }
  }, [contractDetailInfo?.templateFlag]);

  /**
   * 展开收起全部按钮dom
   * @param listOpen 保存的state
   * @param changeOpenSetState 修改state的方法
   * @returns
   */
  const openCloseBtn = (listOpen: Record<string, any>, changeOpenSetState: (obj: Record<string, any>) => void) => {
    return (
      <Button
        className="manageBtntTxtStyle"
        type="link"
        icon={listOpen?.openIdKey?.length > 0 ? <UpCircleOutlined /> : <DownCircleOutlined />}
        size="small"
        onClick={() => {
          if (listOpen?.openIdKey?.length > 0) {
            changeOpenSetState({
              ...listOpen,
              openIdKey: [],
            });
          } else {
            const openList: string[] = [...listOpen?.allOpenKeys];
            changeOpenSetState({
              ...listOpen,
              openIdKey: openList,
            });
          }
        }}
        onMouseOut={onMouseOutBtn}
      >
        {listOpen?.openIdKey?.length > 0 ? '收起全部' : '展开全部'}
      </Button>
    );
  };
  /** tabs标签页 */
  const tabsItem = useMemo(() => {
    let items: any[] = [
      {
        label: '详细信息',
        key: '1',
        children: (
          <UpdateContrractInfo
            changeTextInfo={{
              isUnifiedText,
              setIsUnifiedText,
            }}
            setTabsInfoPaneInfo={setTabsInfoPaneInfo}
            onValuesChange={onValuesChange}
            loadMapInfo={loadMapInfo}
          />
        ),
      },
    ];

    // if (locationID) {
    //   items?.push({
    //     label: '修改记录',
    //     key: '3',
    //     children: (
    //       <ContractChanageList
    //         allOpenChildren={chanageListOpen}
    //         changeOpenChildren={setChangeListOpen}
    //         clickOpenClose={clickOpenClose}
    //       />
    //     ),
    //   });
    // }

    // if (isUnifiedText && pageType != 'detail' && contractDetailInfo?.id) {
    //   items?.push({
    //     label: '合同正文',
    //     key: '9',
    //     children: <ContractOnlyEditingView contractFormInfo={tabsInfoPaneInfo?.formObj} />,
    //   });
    // }

    return items;
  }, [tabsInfoPaneInfo?.tabsPaneKey, locationID, isUnifiedText, curRes, pageType]);

  /** 超预算后不能进行其他操作 */
  const [isBudgetNotBtn, setIsBudgetNotBtn] = useState<boolean>(false);

  /** FORM 表单改变事件 */
  const onValuesChange = (changeValues: Record<string, any>) => {
    const changeKeyStr: string = Object.keys(changeValues)?.toString();
    if (changeKeyStr == 'sumInTax') {
      const maxNumStr: string = changeNumMoneyToChinese(changeValues?.[changeKeyStr]);
      contractForm?.setFieldsValue({
        sumInTaxCN: maxNumStr,
      });
    } else if (changeKeyStr == 'budgetFlag') {
      if (changeValues?.budgetFlag == 0 && isBudgetNotBtn) {
        setIsBudgetNotBtn(false);
      } else if (changeValues?.budgetFlag == 1 && !isBudgetNotBtn) {
        setIsBudgetNotBtn(true);
      }
    }

    // 编辑
    // if (contractDetailInfo?.id) {
    // const changeKeyStr: string = Object.keys(changeValues)?.toString(); //获取变更字段名
    const allFormValues: Record<string, any> = contractForm?.getFieldsValue(); //获取全部填入表单数据
    if (changeKeyStr == 'processList' || changeKeyStr == 'detailList' || changeKeyStr == 'attachList') {
      const changeKeyList: Record<string, any>[] = allFormValues?.[changeKeyStr]; //获取变更的数据源
      const changeKeyIndx: number = changeValues?.[changeKeyStr]?.length - 1;
      if (changeKeyList[changeKeyIndx]['id']) {
        changeKeyList[changeKeyIndx]['modifyFlag'] = '1';
      } else {
        changeKeyList[changeKeyIndx]['modifyFlag'] = '0';
      }
      // if (changeKeyStr == 'processList' && allFormValues?.['sumInTax']) {
      //   // changeKeyList[changeKeyIndx]['paySum'] = (allFormValues?.['sumInTax'] * changeKeyList[changeKeyIndx]['payNum']) / 100;
      //   // const num = (changeKeyList[changeKeyIndx]['paySum'] / allFormValues?.['sumInTax']) * 100;

      //   // changeKeyList[changeKeyIndx]['payNum'] = num.toFixed(2);
      // }

      let newChangeList: Record<string, any>[] = changeKeyList?.filter((item: any) => {
        //已有标记数据
        return (item?.id || item?.key) && item?.modifyFlag != null;
      });

      const newFormJsonList: Record<string, any>[] = contarctJsonList[changeKeyStr]?.length > 0 ? contarctJsonList[changeKeyStr] : [];

      newFormJsonList?.forEach((delItem: any) => {
        if (delItem?.modifyFlag == '2') {
          newChangeList?.push(delItem);
        }
      });

      contractDispatch({
        //保存标记后的代码
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {
          ...contarctJsonList,
          [changeKeyStr]: newChangeList,
        },
      });

      contractForm?.setFieldsValue({
        [changeKeyStr]: allFormValues?.[changeKeyStr],
      });
    }

    if (changeKeyStr == 'payStyle') {
      let newPaylist: Record<string, any>[] = [];
      contractDetailInfo?.processList?.forEach((itemPay: any) => {
        const itemInfo: Record<string, any> = {
          ...itemPay,
          modifyFlag: '2',
        };
        newPaylist?.push(itemInfo);
      });

      contractDispatch({
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {
          ...contarctJsonList,
          processList: [...newPaylist],
        },
      });
    }
    // }
  };

  /** tabs 标签页操作 */
  const contactsTabsExtra = () => {
    if (tabsInfoPaneInfo?.tabsPaneKey == '3') {
      return openCloseBtn(chanageListOpen, setChangeListOpen);
    }
    if (tabsInfoPaneInfo?.tabsPaneKey == '1') {
      return (
        <UpdateContractBottom
          nextBtnShow={isUnifiedText}
          isBudgetNotBtn={isBudgetNotBtn}
          setTabsInfoPaneInfo={setTabsInfoPaneInfo}
          addContractRun={addContractRun}
          editContractRun={editContractRun}
          editRecordContractRun={editRecordContractRun}
          submitRecordContractRun={submitRecordContractRun}
          addAndSubmitContractRun={addAndSubmitContractRun}
          requestType={false}
          loadMapInfo={loadMapInfo}
          position="top"
        />
      );
    }
  };

  return (
    <Tabs
      activeKey={tabsInfoPaneInfo?.tabsPaneKey}
      className={pageStyles['commonTabs']}
      type="card"
      onChange={(activeKey: string) => {
        setTabsInfoPaneInfo({
          ...tabsInfoPaneInfo,
          tabsPaneKey: activeKey,
        });
      }}
      tabBarExtraContent={contactsTabsExtra()}
      items={tabsItem}
    />
  );
};
